<template>
  <div>
    <el-card class="detail-card">
        <div class="mobile-card">
            <!-- 上方操作栏 -->
            <div class="card-header">
                <el-row>
                    <!-- 左侧编辑按钮 -->
                    <el-col :span="12" class="header-left">
                        <el-button type="primary" size="medium" @click="openEditProfileDialog" icon="Edit" class="edit-button">编辑</el-button>
                    </el-col>

                    <!-- 右侧返回按钮 -->
                    <el-col :span="12" class="header-right">
                        <el-button type="primary" @click="goBack">返回</el-button>
                    </el-col>
                </el-row>
            </div>

            <!-- 中间的档案信息展示 -->
            <el-descriptions class="card-body" :column="2" border>
                <el-descriptions-item label="姓名">
                    {{ familyProfile.fullName }}
                </el-descriptions-item>

                <el-descriptions-item label="性别">
                    {{ familyProfile.gender }}
                </el-descriptions-item>

                <el-descriptions-item label="电话">
                    {{ familyProfile.phone }}
                </el-descriptions-item>

                <el-descriptions-item label="住址">
                    {{ familyProfile.address }}
                </el-descriptions-item>

                <el-descriptions-item label="关系">
                    {{ familyProfile.relationship }}
                </el-descriptions-item>

                <el-descriptions-item label="创建时间">
                    {{ familyProfile.createdAt }}
                </el-descriptions-item>
            </el-descriptions>       
        </div>

        <!-- 关系绑定列表 -->
        <el-card class="article-list-card">
          <template #header>
            <div class="article-header">
              <div class="left">
                <el-input
                  v-model="searchQueryElderly"
                  placeholder="请输入老人姓名..."
                  style="width: 200px"
                  @keyup.enter="handleSearch"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </div>
            </div>
          </template>

          <!-- 关系列表表格 -->
          <div class="table-container">
            <el-table 
              :data="relationshipInfo" 
              style="width: 100%" 
              :height="tableHeight"
              :stripe="true"
            >
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column prop="familyName" label="家属姓名" align="center" />
              <el-table-column prop="familyPhone" label="家属联系电话" align="center" />
              <el-table-column prop="status" label="审批情况" align="center">
                <template #default="{ row }">
                    <el-tag :type="getStatusTagType(row.status)" effect="light">
                        {{ row.status }}
                    </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="familyRelationship" label="关系" align="center" />
              <el-table-column label="操作" align="center" fixed="right">
                <template #default="{ row }">
                  <div class="card-actions">
                      <el-button text type="danger" size="small" icon="Delete" @click="handleDelete(row.id)" style="font-size: 12px;">
                          删除
                      </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <div class="pagination">
            <el-config-provider :locale="zhCn">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="total"
                :page-sizes="[5, 10, 20, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
              />
            </el-config-provider>
          </div>
    </el-card>

    </el-card>

    <!-- 编辑弹框 -->
    <el-dialog title="编辑家属档案" v-model="dialogVisible" width="50%">
      <el-form :model="editedProfile" ref="editForm" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="editedProfile.fullName" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="editedProfile.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="电话">
          <el-input v-model="editedProfile.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="住址">
          <el-input v-model="editedProfile.address" placeholder="请输入住址"></el-input>
        </el-form-item>

        <el-form-item label="关系">
          <el-select v-model="editedProfile.relationship" placeholder="请选择与老人之间的关系">
                <el-option label="子女" value="子女"></el-option>
                <el-option label="父母" value="父母"></el-option>
                <el-option label="配偶" value="配偶"></el-option>
                <el-option label="近亲属" value="近亲属"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElConfigProvider } from 'element-plus'
import axios from 'axios';
import { Edit, Plus, Delete } from '@element-plus/icons-vue';
import request from '@/utils/request';

// 获取路由参数
const route = useRoute();
const router = useRouter();
const Family = ref('')
const id = ref(route.params.id);
const userId = ref('');

// 存储家属档案信息
const familyProfile = ref({
  fullName: '',
  gender: '',
  phone: '',
  address: '',
  relationship: '',
  createdAt: ''
});

// 存储编辑的家属档案信息
const editedProfile = ref({
  fullName: '',
  gender: '',
  phone: '',
  address: '',
  relationship: '',
  createdAt: ''
});

// 控制编辑弹框的显示
const dialogVisible = ref(false);

// 根据 id 获取家属档案
const fetchFamilyProfile = async (id) => {
  try {
    const response = await request.get(`/family/${id}`);
    familyProfile.value = response;  // 将返回的数据赋值给 elderlyProfile

    // 将档案数据填充到编辑表单
    editedProfile.value = { ...response };

    // 获取当前家属姓名以及用户id
    Family.value = response.fullName;
    userId.value = response.userId;

    console.log(`家属用户ID: ${userId.value}`);

    refreshTable(userId.value);
  } catch (error) {
    console.error('获取档案信息失败:', error);
  }
};

// 页面加载时获取档案数据
onMounted(() => {
  console.log('用户ID: ${id.value}');
  fetchFamilyProfile(id.value);  // 获取家属档案
});

// 打开编辑弹框
const openEditProfileDialog = () => {
  console.log('触发编辑');
  dialogVisible.value = true;
};

// 提交编辑
const submitEdit = async () => {
  try {
    const id = route.params.id;
    const response = await request.put(`/family/${id}`, editedProfile.value); // 使用 PUT 请求提交编辑数据
    elderlyProfile.value = { ...editedProfile.value }; // 更新档案数据
    dialogVisible.value = false; // 关闭弹框
    ElMessage.success('档案修改成功');
  } catch (error) {
    console.error('修改失败:', error);
    ElMessage.error('修改失败，请稍后重试');
  }
};

// 返回上一页
const goBack = () => {
  router.push('/profile/family')
}

// 关系列表展示
const relationshipInfo = ref([]) // 关系列表
const searchQueryElderly = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1  // 重置页码
  loadRelationships(id.value)  // 重新加载数据
}

// 获取关系列表
const loadRelationships = async (id) => {
  try {
    if (!id) {
      ElMessage.error('家属ID不存在')
      return
    }

    // 调用搜索接口，使用路由参数中的作者ID
    const response = await request.get(`/binding`, {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        familyName: Family.value,  // 家属姓名
        elderlyName: searchQueryElderly.value // 老人姓名
      }
    });

    // console.log('API 返回的数据:', response.data);
    relationshipInfo.value = response.records
    total.value = response.total

  } catch (error) {
    console.error('加载关系列表失败:', error)
    ElMessage.error('加载关系列表失败')
  }
}

// 重置搜索
const handleReset = () => {
  searchQueryElderly.value = ''  // 清空搜索关键字
  currentPage.value = 1   // 重置页码
  refreshTable(userId.value)         // 重新加载数据
}

// 刷新老人关系列表
const refreshTable = async (id) => {
  try {
    const response = await request.get(`/binding/self/list?familyUserId=${id}&page=${currentPage.value}&size=${pageSize.value}`)
    relationshipInfo.value = response.records
    total.value = response.total
  } catch (error) {
    console.error('获取老人绑定家属列表失败:', error)
  }
}

// 删除单个关系
const handleDelete = async (id) => {
  // 弹出确认删除的弹框
  ElMessageBox.confirm(
    '您确定要删除此家属绑定吗？', // 提示文本
    '警告', // 标题
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning', // 设置为警告类型
    }
  )
    .then(async () => {
      // 用户点击确认时，执行删除操作
      try {
        const response = await request.delete(`binding/admin/${id}`);  // 删除请求
        ElMessage.success('删除成功');
        refreshTable(userId.value);  // 删除后重新获取数据
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请稍后重试');
      }
    })
    .catch(() => {
      // 用户点击取消时的操作
      ElMessage.info('删除操作已取消');
    });
};

// 获取审批状态
const getStatusTagType = (status) => {
  switch (status) {
    case '审批通过':
      return 'success';
    case '待审批':
      return 'warning';
    case '已拒绝':
      return 'danger';
    default:
      return 'info';
  }
};

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}  
</script>

<style scoped>
.el-card {
  width: 100%;
  height: 80vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  max-height: 600px;
  /* 限制卡片的最大高度，可以根据需要调整 */
  overflow-y: auto;
  /* 启用垂直滚动条 */
}

.mobile-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease, transform 0.3s ease;
  max-height: 400px;
  /* 限制卡片的最大高度，可以根据需要调整 */
  overflow-y: auto;
  /* 启用垂直滚动条 */
}

.mobile-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

/* 调整在住状态标签样式 */
.status-tag {
  font-size: 28px;
  /* 增加字体大小 */
  padding: 12px 24px;
  /* 增加内边距，使标签更大 */
}

/* 调整编辑按钮样式 */
.edit-button {
  font-size: 28px ！ !important;
  /* 增加字体大小 */
  padding: 12px 24px !important;
  /* 增加内边距，让按钮更大 */
}


/* 卡片上方样式 */
.card-header {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.header-left {
  display: flex;
  justify-content: flex-start;
  /* 左侧对齐 */
  align-items: center;
  gap: 4px;
}

.header-right {
  display: flex;
  justify-content: flex-end;
  /* 右侧对齐 */
  text-align: right;
  /* 按钮右对齐 */
}

.el-tag {
  font-size: 14px;
}

.el-button {
  padding: 8px 16px;
  font-size: 14px;
}

/* 卡片下方样式 */
.card-body {
  padding: 16px 0;
  border-radius: 12px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06) !important;
}

::v-deep .el-descriptions__cell {
  padding: 6px 8px !important;
  font-size: 13px !important;
}

::v-deep .el-descriptions__content {
  color: #333 !important;
}


/* 关系列表 */
.article-list-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  width: 100%;
  margin-bottom: 20px;
}

.article-list-card :deep(.el-card__body) {
  padding: 20px;
}

.el-table {
  flex: 1;
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.article-header .left {
  display: flex;
  gap: 10px;
  align-items: center;
}

.article-header .right {
  display: flex;
  gap: 10px;
}

.content-preview {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  padding: 0 10px;
}

.pagination {
  margin-top: 0;
  /* 修改分页器的上边距 */
  padding: 0;
  /* 移除内边距 */
  display: flex;
  justify-content: flex-end;
}

.table-container {
  width: 100%;
  min-width: 0;
  overflow: hidden;
  margin-bottom: 20px;
}

/* 表格样式 */
:deep(.el-table) {
  width: 100% !important;

  .el-table__empty-block {
    width: 100% !important;
    min-height: 54px;
    height: 54px;
  }

  .el-table__empty-text {
    line-height: 54px;
  }

  .el-table__row {
    height: 54px;
  }

  /* 移除表格边框 */
  &::before {
    display: none;
  }

  /* 移除单元格边框 */
  .el-table__cell {
    border: none;
  }

  /* 添加表格外边框 */
  border: 1px solid #dcdfe6;

  /* 条纹样式 */
  .el-table__row--striped {
    background-color: var(--el-table-row-hover-bg-color);
  }
}

/* 修改表格行高度为自适应 */
:deep(.el-table__row) {
  height: auto !important;

  >td {
    padding: 10px 0;
  }
}

/* 修改表格内容单元格样式 */
:deep(.content-preview) {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
  max-height: none;
  padding: 10px;
}
</style>
